package com.example.tiantian.application;

import java.util.ArrayList;
import java.util.List;

import com.example.tiantian.BaseActivity;
import com.example.tiantian.OnReceiveListener;
import com.example.tiantian.R;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.TextView;

public class ApplicationActivity extends BaseActivity implements Callback, OnClickListener, OnItemClickListener {

    Button btnUser;
    Button btnSystem;

    TextView txtInfo;

    FrameLayout layout;
    GridView gvApp;

    PackageManager packageManager;

    List<ApplicationInfo> userApp;
    List<ApplicationInfo> sysApp;

    Handler handler;

    AppAdapter adapter;

    boolean isGrid = true;

    ApplicationReceiver receiver;

    @Override
    protected void init() {
        setContentView(R.layout.activity_application);

        btnSystem = (Button) findViewById(R.id.app_btn_system);
        btnUser = (Button) findViewById(R.id.app_btn_user);

        txtInfo = (TextView) findViewById(R.id.app_txt_info);

        gvApp = (GridView) findViewById(R.id.app_grid);
        layout = (FrameLayout) findViewById(R.id.app_load);

        packageManager = getPackageManager();

        handler = new Handler(this);

        userApp = new ArrayList<ApplicationInfo>();
        sysApp = new ArrayList<ApplicationInfo>();

        btnUser.setEnabled(false);
        btnSystem.setEnabled(true);

        receiver = new ApplicationReceiver();
    }

    @Override
    protected void loadData() {
        new Thread() {
            @Override
            public void run() {
                List<ApplicationInfo> apps = packageManager.getInstalledApplications(0);
                for (ApplicationInfo info : apps) {
                    if ((info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0
                            || (info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
                        userApp.add(info);
                    } else {
                        sysApp.add(info);
                    }
                }

                handler.sendEmptyMessage(0);
            }
        }.start();
    }

    @Override
    protected void event() {
        txtInfo.setOnClickListener(this);
        btnSystem.setOnClickListener(this);
        btnUser.setOnClickListener(this);

        gvApp.setOnItemClickListener(this);

    }

    @Override
    public boolean handleMessage(Message msg) {
        if (msg.what == 0) {
            layout.setVisibility(View.GONE);

            adapter = new AppAdapter(this, userApp, isGrid, packageManager);
            gvApp.setAdapter(adapter);
            txtInfo.setText(getString(R.string.application_user) + ":" + userApp.size());
        }
        return false;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.app_txt_info:
            isGrid = !isGrid;
            Drawable right = getResources().getDrawable(isGrid ? R.drawable.grids : R.drawable.list);
            right.setBounds(0, 0, right.getMinimumWidth(), right.getMinimumHeight());
            txtInfo.setCompoundDrawables(null, null, right, null);
            gvApp.setNumColumns(isGrid ? 3 : 1);
            adapter.changeShowType(isGrid);
            break;
        case R.id.app_btn_user:
            adapter.changeAppList(userApp);
            btnUser.setEnabled(false);
            btnSystem.setEnabled(true);
            txtInfo.setText(getString(R.string.application_user) + ":" + userApp.size());
            break;
        case R.id.app_btn_system:
            adapter.changeAppList(sysApp);
            btnUser.setEnabled(true);
            btnSystem.setEnabled(false);
            txtInfo.setText(getString(R.string.application_system) + ":" + sysApp.size());
        default:
            break;
        }
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        final ApplicationInfo info = (ApplicationInfo) parent.getAdapter().getItem(position);
        new AlertDialog.Builder(this).setTitle(info.loadLabel(packageManager))
                .setItems(getResources().getStringArray(R.array.app_dialog), new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                        case 0:
                            try {
                                StringBuffer sb = new StringBuffer();
                                sb.append("程序包名:").append(info.packageName).append("\n").append("版本号")
                                        .append(packageManager.getPackageInfo(info.packageName, 0).versionCode)
                                        .append("\n").append("版本名称:")
                                        .append(packageManager.getPackageInfo(info.packageName, 0).versionName)
                                        .append("\n");
                                new AlertDialog.Builder(ApplicationActivity.this)
                                        .setTitle(info.loadLabel(packageManager)).setIcon(info.loadIcon(packageManager))
                                        .setMessage(sb.toString()).setPositiveButton("确定", null).show();
                            } catch (NameNotFoundException e) {
                                Log.d(getLocalClassName(), e.toString());
                            }
                            break;
                        case 1:
                            if (info.packageName.equals(ApplicationActivity.this.getPackageName())) {
                                return;
                            }
                            Intent delete = new Intent();
                            delete.setAction(Intent.ACTION_DELETE);
                            delete.setData(Uri.parse("package:" + info.packageName));
                            ApplicationActivity.this.startActivity(delete);

                            // 注册 应用安装/卸载 广播接收器
                            IntentFilter filter = new IntentFilter();
                            filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
                            filter.addDataScheme("package");

                            ApplicationActivity.this.registerReceiver(receiver, filter);
                            receiver.SetOnReceiveListener(new OnReceiveListener() {

                                @Override
                                public void onReceive(Context context, Intent intent) {
                                    // 把被删除的应用在集合内删除 ，同时更新GV显示
                                    if (info.packageName.equals(intent.getData().getSchemeSpecificPart())) {
                                        userApp.remove(info);

                                        adapter.changeAppList(userApp);
                                        adapter.notifyDataSetChanged();
                                        txtInfo.setText(getString(R.string.application_user) + ":" + userApp.size());
                                    }

                                    // 获取了消息之后 直接注销自己
                                    ApplicationActivity.this.unregisterReceiver(receiver);
                                }
                            });
                            break;
                        case 2:
                            if (info.packageName.equals(ApplicationActivity.this.getPackageName())) {
                                return;
                            }
                            Intent start = packageManager.getLaunchIntentForPackage(info.packageName);
                            if (start != null) {
                                startActivity(start);
                            } else {
                                ApplicationActivity.this.toast("Start " + info.loadLabel(packageManager) + " failed");
                            }
                            break;
                        default:
                            break;
                        }
                    }
                }).show();
    }

}
